package com.ruike.alisurface.ui.mainPage;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.InitFinishCallback;
import com.cunoraz.gifview.library.GifView;
import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.Ttys3Utils;
import com.ruike.alisurface.Serials.outGoods.ShengJiangJiUtils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.http.AppUpdateHttp;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.mqtt.MQTTService;
import com.ruike.alisurface.services.AppRunMonitoringService;
import com.ruike.alisurface.services.MyIntentService;
import com.ruike.alisurface.services.NetWorkListenerService;
import com.ruike.alisurface.ui.setting.StopSellingActivity;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.DeviceUtils;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.FileUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.voodoo.lib_utils.imageLoader.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;

import static com.ruike.alisurface.utils.ShareKey.BASEUSERID;
import static com.ruike.alisurface.utils.ShareKey.IC2_SLOT_NUM;
import static com.ruike.alisurface.utils.ShareKey.SERVICE_TEL;
import static com.ruike.alisurface.utils.ShareKey.Type_sendPlankVersion;

/**
 * Author: voodoo
 * CreateDate: 2020-03-26 026 下午 12:45
 * Description: APP启动页
 */
public class SystemStartActivity extends BaseAty {

    @BindView(R.id.systemStart_pageBg_rlayout)
    RelativeLayout pageBgRlayout;
    @BindView(R.id.systemStart_show_gifv)
    GifView showGifv;
    @BindView(R.id.systemStart_status_tv)
    TextView statusTv;
    @BindView(R.id.systemStart_sn_tv)
    TextView snTv;
    @BindView(R.id.systemStar_sn_code)
    ImageView sn_code;

    boolean isInit = false; // 已经初始化
    private String baseUserId = ShareUtils.getInstance().getString(BASEUSERID, "RK_test"); // 用户类型，默认是未分配用户

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_system_start;
    }

    @Override
    protected void initViews() {
        L.i("启动页==" + this.getClass().getName());
        showGifv.setVisibility(View.VISIBLE);
        showGifv.play();
        statusTv.setText(new StringBuffer(getResources().getString(R.string.checkingNetworkStr)));
        snTv.setText(new StringBuffer(getResources().getString(R.string.deviceSnStr)).append(DeviceUtils.getDeviceSn()));
        L.i("机器序列号:" + DeviceUtils.getDeviceSn());
    }

    @Override
    protected void initData() {
        writeShareFile(); // 写入共享文件数据

        // 如果不存在key，则设将key和默认售卖的标志存进去
        if (!ShareUtils.getInstance().containsKey(ShareKey.IS_STOP_SELLING)) {
            ShareUtils.getInstance().putBoolean(ShareKey.IS_STOP_SELLING, false);
        }
        // 获取IS_STOP_SELLING，如果停止售卖状态则跳转至相应界面，停止之后的所有操作
        if (ShareUtils.getInstance().getBoolean(ShareKey.IS_STOP_SELLING)) { // 停止售卖
            startActivity(StopSellingActivity.class, null);
            return;
        }

        setDataSNcode(sn_code);
        startService(new Intent(this, AppRunMonitoringService.class)); // 启动APP运行检测服务
//        InitSdk();
        Intent intent = new Intent(this, MyIntentService.class);
        startService(intent);
        Ttys3Utils.getInstance().sendCheckWKVersion(6);
        SystemClock.sleep(600);
        Ttys3Utils.getInstance().sendCheckVersion(10);

        boolean isOfflineRestartApp = ShareUtils.getInstance().getBoolean(ShareKey.IS_OFFLINE_RESTART_APP, true); // 断网重启app
        L.i("断网重启app" + isOfflineRestartApp);
        if (isOfflineRestartApp) {
            ShareUtils.getInstance().putBoolean(ShareKey.IS_OFFLINE_RESTART_APP, true);
        } else {
            ShareUtils.getInstance().getBoolean(ShareKey.IS_OFFLINE_RESTART_APP, false);
        }

        // 设置默认购买数量
        if (!ShareUtils.getInstance().containsKey(ShareKey.PURCHASE_COUNT)) {
            ShareUtils.getInstance().putInt(ShareKey.PURCHASE_COUNT, Constant.DefaultData.PURCHASE_COUNT);
        }
        // 设置默认货道显示
        if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 0) == 0) {
            ShareUtils.getInstance().putInt(ShareKey.IS_SHOP_TYPE, 1);
        }
        // 设置默认 轮播图广告
        if (ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE) == Constant.ADV_TYPE_NONE) {
            ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_IMAGE);
        }

    }

    /**
     * 刷脸支付itosdk植入
     */
    private void InitSdk() {
        try {
            APIManager.getInstance().initialize(getApplicationContext(), "2088821660782062", new InitFinishCallback() {
                @Override
                public void initFinished(boolean b) {
                    L.i("刷脸支付 验证是否注册 " + b);

                }
            });
        } catch (APIManager.APIInitException e) {
            L.e("刷脸支付 APIInitException " + e);

        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        isInit = true;
    }

    @Override
    public void onNetChange(int netMobile, boolean isConnect) {
        statusTv.setText(isConnect ? getResources().getString(R.string.networkConnectionSuccessStr) : getResources().getString(R.string.networkConnectionFailureStr));

        if (isConnect && isInit && !ShareUtils.getInstance().getBoolean(ShareKey.IS_STOP_SELLING)) {
            startService(new Intent(this, MQTTService.class)); // 启动Mqtt服务
            Intent intent = new Intent(this, NetWorkListenerService.class);
            startService(intent);

            isInit = false;
            statusTv.setText(getString(R.string.system_init_data));
            new MyCountDownTimer(2000, 2000) {
                @Override
                public void onTick(long millisUntilFinished) {
                }

                @Override
                public void onFinish() {
                    MchApiHttp.getMchBySn(SystemStartActivity.this); // 获取机器信息
                }
            }.start();
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        try {
            JSONObject object = new JSONObject(requestJsonStr);
            String data = object.optString("data");

            if (requestUrl.endsWith("getAppVersion")) { // 获取APP的版本
                JSONArray jsonArray = new JSONArray(data);
                JSONObject o = (JSONObject) jsonArray.get(0);
                String version = o.getString("Version");
                L.i("onSuccess:程序版本号： " + version);
                ShareUtils.getInstance().putString(ShareKey.VERSION_NUM, version);
                return;
            }
            if (requestUrl.contains("geMchBySn")) {  // 根据机器SN获取机器号MchId
                JSONObject mchObject = new JSONObject(data);
                String idStr = mchObject.optString("Id");
                ShareUtils.getInstance().putString(ShareKey.MCH_ID, idStr);
                L.i("onsuccess: MchId：" + idStr);
                String service_tel = mchObject.optString("service_tel");
                if (!service_tel.equals("null") && service_tel != null && !service_tel.isEmpty()) {
                    L.i("===service_tel==" + service_tel);
                    ShareUtils.getInstance().putString(SERVICE_TEL, service_tel);
                } else {
                    ShareUtils.getInstance().putString(SERVICE_TEL, getString(R.string.noPhoneStr));
                }
                baseUserId = mchObject.optString("BaseUserId");
                ShareUtils.getInstance().putString(BASEUSERID, baseUserId);
                L.i("==BaseUserId==" + baseUserId);
                int IC2_max_lattices = mchObject.optInt("IC2_max_lattices");
                L.i("==货道柜设置余数==" + IC2_max_lattices);
                if (IC2_max_lattices > 0) {
                    ShareUtils.getInstance().putInt(IC2_SLOT_NUM, IC2_max_lattices);
                }
                AppUpdateHttp.tellServiceAppVersionInfo(this);
                SystemClock.sleep(2000);

                if (Constant.machineType == 1) { // IC2
                    doNext();
                } else if (Constant.machineType == 2) { // 升降机
                    statusTv.setText("正在初始化升降机...");
                    ShengJiangJiUtils.setOnSJJListener(new ShengJiangJiUtils.OnSJJInitListener() {
                        @Override
                        public void initSuccess() {
                            doNext();
                        }

                        @Override
                        public void initFailure() {
                            statusTv.setText("初始化失败，重启App...");
                            new MyCountDownTimer(2000, 2000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                }

                                @Override
                                public void onFinish() {
                                    reStartApp();
                                }
                            }.start();
                        }
                    });
                    ShengJiangJiUtils.init();
                }

                return;
            }

            if (requestUrl.endsWith("TellService_AppVersion_Info")) { // 上报当前APP版本信息
                // 暂无需处理上报后回传的信息
                return;
            }

        } catch (JSONException e) {
            L.i("onSuccess:JSON 字符串异常，一般不会在此出现该问题： " + e.toString());
            e.printStackTrace();
        }

    }

    /**
     * 下一步
     */
    private void doNext() {
        if (baseUserId.equals("RK_test")) {
            startActivity(BindMachineActivity.class, null);
            finish();
            return;
        }
        startCountdownTimer(0, null, null);
    }

    @Override
    public void onError(String url, String errorMsg) {
        super.onError(url, errorMsg);
        if (url.endsWith("getAppVersion")) { // 获取APP的版本
            statusTv.setText(getString(R.string.notGetVersionStr));
            return;
        }

        if (url.contains("geMchBySn")) {  // 根据机器SN获取机器号MchId
            statusTv.setText(errorMsg);
            return;
        }

        if (url.endsWith("TellService_AppVersion_Info")) { // 上报当前APP版本信息
            // 暂无需处理上报后回传的信息
            return;
        }
    }

    /**
     * 写入共享文件
     */
    private void writeShareFile() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mainPackageName", BuildConfig.APPLICATION_ID); // 程序包名
            jsonObject.put("mainPackageType", Constant.APP_TYPE); // 程序类型
            L.i("写入共享文件", "文件地址：" + Constant.MAIN_PACKAGE_NAME_FILE_PATH, "写入内容：" + jsonObject.toString());

            new Thread(new Runnable() {
                @Override
                public void run() {
                    FileUtils.writeFileFromString(Constant.MAIN_PACKAGE_NAME_FILE_PATH, jsonObject.toString(), false);
                    FileUtils.CteateFileFromString(Environment.getExternalStorageDirectory()
                            + File.separator + "picture" + File.separator + "adv");
                    FileUtils.CteateFileFromString(Environment.getExternalStorageDirectory()
                            + File.separator + "picture" + File.separator + "Vedio");
                }
            }).start();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals(Type_sendPlankVersion)) {
            String msg = event.getMessage();
            L.i("tjf-sendPlankVersion--", msg);
            String[] pb = msg.split("-");
            /*"MV", "Fir", "Sec", "Thr" "T"*/
            if (pb[0].equals("MV")) {
                ShareUtils.getInstance().putString("MV", pb[1]);
                Ttys3Utils.getInstance().sendCheckVersion(11);
            } else if (pb[0].equals("Fir")) {
                ShareUtils.getInstance().putString("Fir", pb[1]);
                Ttys3Utils.getInstance().sendCheckVersion(12);
            } else if (pb[0].equals("Sec")) {
                ShareUtils.getInstance().putString("Sec", pb[1]);
                Ttys3Utils.getInstance().sendCheckVersion(13);
            } else if (pb[0].equals("Thi")) {
                ShareUtils.getInstance().putString("Thr", pb[1]);
            }
        }
    }

    /**
     * 重启自身APP
     */
    public void reStartApp() {
        Intent intent = new Intent(this, SystemStartActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    protected void onStop() {
        super.onStop();
        showGifv.pause();
        L.i("onStop.showShop--", Constant.showShop);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
